package handler

import (
	"gitee.com/sansaniot/ssiot-core/httpmvc"
	"gitee.com/sansaniot/ssiot-core/httpmvc/api"
	"github.com/gin-gonic/gin"
	"ssadmin/common/constant"
	"ssadmin/common/utils"
	"ssadmin/internal/admin/models"
	globalUtil "ssadmin/internal/admin/utils"
)

func AuthenticatorFromAccount(c *gin.Context) (interface{}, error) {
	log := api.GetRequestLogger(c)
	db, err := httpmvc.GetOrm(c)
	tenant := c.GetHeader(constant.CacheKeyTenant)
	tenant = "public"

	var loginVals LoginUser
	if err = c.ShouldBind(&loginVals); err != nil {
		loginVals.Username, _ = c.GetPostForm("username")
		loginVals.Password, _ = c.GetPostForm("password")
		loginVals.Phone, _ = c.GetPostForm("phone")
		loginVals.Code, _ = c.GetPostForm("code")
	}

	loginVals.Tenant = tenant
	var userInfo models.User
	var errMsg string
	var e error
	if len(loginVals.Username) > 0 && len(loginVals.Password) > 0 {
		// 用户密码登录
		userInfo, e = loginVals.LoginUsername(db)
		if e != nil {
			c.Set("loginError", "用户名或密码错误")
			return nil, nil
		}
		// 校验密码
		errMsg = validPwd(c, loginVals, &userInfo)
	} else if len(loginVals.Phone) > 0 && len(loginVals.Code) > 0 {
		// 手机号验证码登录
		userInfo, e = loginVals.LoginUserPhone(db)
		if e != nil {
			c.Set("loginError", "手机号或验证码错误")
			return nil, nil
		}
		// 校验验证码
		//codeData := global.CacheOperator.Get(constant.PrefixAuthCode + loginVals.Phone)
		//if len(codeData) == 0 || globalUtil.GetCommUtil().BytesToMap([]byte(codeData))["code"] != loginVals.Code {
		//	errMsg = "验证码过期或者无效"
		//}
	} else {
		c.Set("loginError", "登录请求参数异常")
		return nil, nil
	}
	defer func() {
		LoginLogToDB(c, "用户登录", userInfo)
	}()

	if len(errMsg) > 0 {
		log.Warn(errMsg)
		c.Set("loginError", errMsg)
		return nil, nil
	}

	//设置用户信息缓存
	_ = loginVals.GetProfile(db, &userInfo)
	userInfo.Tenant = tenant
	profile := map[string]interface{}{
		constant.CacheKeyUserDeptIds:  userInfo.DeptIds,
		constant.CacheKeyUserDeptName: userInfo.DeptName,
		constant.CacheKeyUserRoleIds:  userInfo.RoleId,
		constant.CacheKeyAgencyId:     userInfo.Agency,
		constant.CacheKeyUserId:       userInfo.UserId,
		constant.CacheKeyUserName:     userInfo.Username,
		constant.CacheKeyCreator:      userInfo.Creator,
		constant.CacheKeyCreatorId:    userInfo.CreatorId,
		constant.CacheKeyAvatar:       userInfo.Avatar,
		constant.CacheKeyAlias:        userInfo.Alias,
	}
	globalUtil.SetUserProfile(userInfo.Username, profile)
	c.Set(constant.CacheKeyUserInfo, profile)
	return userInfo, nil
}

func validPwd(c *gin.Context, loginVals LoginUser, user *models.User) string {
	var inputPwd, decodePwd string
	aesKey := "aes" + c.GetHeader("authtimestamp")

	//先解密
	decodePwd, err := utils.AesDecrypt(loginVals.Password, aesKey)
	if err != nil {
		return "密码错误"
	}
	inputPwd = utils.Md5Pwd(decodePwd, loginVals.Username+decodePwd)

	if inputPwd != user.Password {
		return "用户名或密码错误！"
	}

	if "0" == user.Status {
		return "账号已被锁定,请联系管理员！"
	}
	return ""
}
